const app = getApp()

Page({
  data: {
    id: '',
    shop: null,
    categories: [],
    products: [],
    currentCategory: null,
    loading: true,
    isNoticeExpanded: false
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ 
        id: options.id,
        loading: true  // 初始设置为加载状态
      })
      this.loadShopDetail(options.id)
      this.loadCategories(options.id)
    }
  },

  // 加载店铺详情
  async loadShopDetail(id) {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('shops').doc(id).get()
      
      // 加载最新的5条公告
      const notices = await db.collection('notices')
        .where({ shopId: id })
        .orderBy('createTime', 'desc')
        .limit(3)
        .get()
      
      // 加载最新的3篇文章，并处理时间格式
      const articles = await db.collection('articles')
        .where({ shopId: id })
        .orderBy('createTime', 'desc')
        .limit(3)
        .get()

      // 处理文章数据
      const formattedArticles = articles.data.map(article => ({
        ...article,
        description: article.content.substring(0, 50) + '...', // 截取前50个字符作为描述
        createTime: this.formatTime(article.createTime) // 格式化时间
      }))
      
      this.setData({ 
        shop: {
          ...data,
          notices: notices.data,
          articles: formattedArticles
        },
        loading: false
      })

      wx.setNavigationBarTitle({
        title: data.name
      })
    } catch (error) {
      console.error('加载店铺详情失败：', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return ''
    const date = new Date(timestamp)
    const now = new Date()
    const diff = now - date

    // 如果是今天
    if (diff < 24 * 60 * 60 * 1000) {
      const hours = date.getHours()
      const minutes = date.getMinutes()
      return `今天 ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
    }

    // 如果是昨天
    if (diff < 48 * 60 * 60 * 1000) {
      return '昨天'
    }

    // 如果是今年
    if (date.getFullYear() === now.getFullYear()) {
      return `${date.getMonth() + 1}月${date.getDate()}日`
    }

    // 其他情况
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
  },

  // 加载分类
  async loadCategories(shopId) {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('categories')
        .where({
          shopId: shopId
        })
        .orderBy('sort', 'asc')
        .get()
      
      if (data && data.length > 0) {
        this.setData({ 
          categories: data,
          currentCategory: data[0]._id
        }, () => {
          // 加载第一个分类的商品
          this.loadProducts(data[0]._id)
        })
      }
    } catch (error) {
      console.error('加载分类失败：', error)
    }
  },

  // 加载商品
  async loadProducts(categoryId) {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('products')
        .where({
          shopId: this.data.id,
          categoryId: categoryId,
          status: 'on'
        })
        .orderBy('createTime', 'desc')
        .get()
      
      this.setData({ products: data })
    } catch (error) {
      console.error('加载商品失败：', error)
    }
  },

  // 切换分类
  onCategoryChange(e) {
    const { id } = e.currentTarget.dataset
    if (id === this.data.currentCategory) {
      return
    }
    this.setData({ currentCategory: id })
    this.loadProducts(id)
  },

  // 跳转到商品详情
  goToDetail(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/products/detail?id=${id}`
    })
  },

  // 拨打电话
  callShop() {
    const { phone } = this.data.shop
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },

  // 查看地图
  viewLocation() {
    // TODO: 添加地图功能
    wx.showToast({
      title: '地图功能开发中',
      icon: 'none'
    })
  },

  // 切换公告展开状态
  toggleNotice(e) {
    const { index } = e.currentTarget.dataset
    const key = `shop.notices[${index}].expanded`
    this.setData({
      [key]: !this.data.shop.notices[index].expanded
    })
  },

  // 查看更多文章
  viewMoreArticles() {
    wx.navigateTo({
      url: `/pages/articles/list?shopId=${this.data.id}`
    })
  },

  // 查看文章详情
  viewArticle(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/articles/detail?id=${id}&shopId=${this.data.id}`
    })
  },

  // 查看公告详情
  viewNoticeDetail(e) {
    const { index } = e.currentTarget.dataset
    const notice = this.data.shop.notices[index]
    
    wx.showModal({
      title: notice.type || '店铺公告',
      content: notice.content,
      showCancel: false,
      confirmText: '知道了'
    })
  }
}) 